$(function(){
	//普通用户中心免费咨询请求
	// 弹窗样式
  function layerCss(){
    $(".layui-layer").css("border-radius","10px")
    $(".layui-layer-setwin .layui-layer-close2").css({"right":"-40px","top":"0px"});
    $(".layui-layer-ico").css("background","url("+jumpUrl+"/img/question2/iconlayer.png)");
  }
	
	//取消
	$(document).on( "click", ".js_cancel", function(e) {
		var url = $(this).attr("data-href");
		var _token = $("input[name='_token']").val();
	    $.post(url,{"_token":_token},function(data){
	      },'json').error(function(data) {
	          var obj = $.parseJSON(data.responseText);
	          layer.msg(obj.error_messages);
	      }).success(function(data) {
	          layer.msg(data.data);
	          window.location.href=jumpcancel;
	      });
	      stopDefault(e);
	});
	
	//确认完成
	$(document).on( "click", ".js_to_complete", function(e) { 
		var url = $(this).attr("data-href");
		var user_id = $(this).attr("data-id");
		var _token = $("input[name='_token']").val();
	    $.post(url,{"user_id":user_id,"_token":_token},function(data){
	      },'json').error(function(data) {
	          var obj = $.parseJSON(data.responseText);
	          $.each(obj.error_messages, function(i, item){
	          });
	      }).success(function(data) {
	          layer.msg(data.data);
	          window.location.href=jumpevaluation;
	      });
	      stopDefault(e);
	});
	
	//对咨询回复的评分
	$(document).on("mouseover", ".serviceEvaluation img", function(){
	  	var index = $(this).index();
	  	var	starOnUrl = jumpUrl+"/img/star-on.png";
		var	starOffUrl = jumpUrl+"/img/star-off.png";
	  	$(this).attr("src",starOnUrl);
	  	$(this).prevAll().attr("src",starOnUrl);
	  	$(this).nextAll().attr("src",starOffUrl);
	});
	  
	$(document).on("click", ".serviceEvaluation img", function(){
		$('.num-score').text($(this).index()+1);
		$('#evaluate_score').val($(this).index()+1);		
	})
    $(document).on("mouseleave", ".serviceEvaluation", function(){
	  var index = parseInt($('.num-score').text());
	  var starOffUrl = jumpUrl+"/img/star-off.png";
	  var starOnUrl = jumpUrl+"/img/star-on.png";
	  $('.serviceEvaluation img:eq('+index+')').prevAll().attr("src",starOnUrl);
	  $('.serviceEvaluation img:eq('+index+')').attr("src",starOffUrl);
	  $('.serviceEvaluation img:eq('+index+')').nextAll().attr("src",starOffUrl);
	});
	  
	var to_complete = $("#to_complete");
	//用户对咨询的评价
	var stch=false; //防止多次提交的全局变量
	$(document).on("click",".subComplete",function(e){
		var starOnUrl = jumpUrl+"/img/star-on.png";
		var starOffUrl = jumpUrl+"/img/star-off.png";
		var score = $('#evaluate_score').val();
	    var comment =$.trim($(".js_comment_txtarea").val());
	    var str="";
	    if(comment.length < 0){
	        layer.msg('提交的内容不能为空！');
	    }else if(score<1){
	    	layer.msg('评分在1-5分之间'); 
	    }else{
	        if (stch==true){
	            layer.msg('请不要重新提交数据!');
	        }else{
	            stch=true;
	            $.post(to_complete[0].action, to_complete.serialize(),
		            function(data){
		            },'json').error(function(data) {
		                var obj = $.parseJSON(data.responseText);
		                // $.each(obj.error_messages, function(i, item){
		                //   layer.msg(item[0]);
		                // });
		            }).success(function(data) {
		                layer.msg("评价成功");
		            	window.location.href=jumpNext;          
		                stch=false;
	            });
	        }
	    }
	    stopDefault(e);
	});
	  
		
	//删除
	$(document).on( "click", ".delete-question", function(e) {
		var url = $(this).attr("data-href");
		var user_id = $(this).attr("data-id");
		var _token = $("input[name='_token']").val();
	    $.post(url,{"user_id":user_id,"_token":_token},function(data){
	      },'json').error(function(data) {
	          var obj = $.parseJSON(data.responseText);
	          $.each(obj.error_messages, function(i, item){
	          });
	      }).success(function(data) {
	          layer.msg(data.data);
	          window.location.href=jumpdelete;
	      });
	      stopDefault(e); 
	});
		
	//联系律师
	$(".to_ask").click( function (e) {
		 var iTop = (window.screen.availHeight-600)/2; //获得窗口的垂直位置;
		 var iLeft = (window.screen.availWidth-600)/2; //获得窗口的水平位置;
		 chatUrl = $(this).attr("data-href");
		 window.open (chatUrl, "", "height=600, width=600, top="+iTop+", left="+iLeft+", toolbar =no, menubar=no, scrollbars=no, resizable=no, location=yes, status=no")

	});
		
	//选择付款方式
	$('.icon02').click(function(){
	    $('.icon02').removeClass('icon04');
	    $(this).addClass('icon04');
	});
	//付款请求
	$(document).on('click', '.submit-but', function(e){
		var loading = layer.msg('加载中...', {icon: 16});
		var question_id = $(this).attr("data-id");
		var type = $('.checkedIcon').attr('data-href');
		var type_subject = $("#type").text();
		var type_body = $("#type").text();
		if (type == "wallet") {
			var url = jumpUrl+"/center/question/"+question_id+"/pay/wallet";
		    $.post(url,function(data){
		      },'json').error(function(data) {
		          var obj = $.parseJSON(data.responseText);
		          layer.msg(obj.error_messages);
		      }).success(function(data) {
		          layer.msg(data.data);
		          window.location.href=jumpUrl+"/center/customer/my_order";
		      });
		}else if(type == "weixin"){
			var params = {};
			params.device = 'pc';   // 客户端
			params.channel = 'wx_pub_qr';   //支付方式
			params.amount = totalMoney*100;  //支付金额乘以100
			params.subject = type_subject;   //商品标题
			params.body = type_body;  //商品描述
			params.product_id = question_id;  //微信公众账号扫码支付 订单id
			params.current_user_id = current_user_id;  //当前id
			params.metadata = {};  
			params.metadata.pay_type = 'order';  //订单类型
			params.metadata.question_id = question_id;  //订单id
			var wechat_qr_params_url = jumpUrl+"/payment_gateway/charge";
			var qr_code_url;
		    $.post(wechat_qr_params_url,params,function(data){
		      },'json').error(function(data) {
		          var obj = $.parseJSON(data.responseText);
		          layer.msg(obj.error_messages);
		      }).success(function(data) {
			      	console.log(data);
			      	qr_code_url = data.credential.wx_pub_qr;
			      	  charge_id = data.id;
			      	  qr_payment_popup();
			      	  check_payment(charge_id);
			      	  var str = ''
			      	  str +='<img src="http://paysdk.weixin.qq.com/example/qrcode.php?data='+qr_code_url+'" style="width:250px;height:250px;border-radius: 10px;" />';
			      	  str +='<p style="text-align:center;font-size:20px;">[ 扫描二维码支付 ]</p>';
			      	$(".content-box").append(str);
		      });
		}else if(type == "alipay"){
			var params = {};
			params.device = 'pc';  // 客户端
			params.channel = 'alipay_qr';  //支付方式
			params.amount = totalMoney*100; //支付金额乘以100
			params.subject = type_subject;  //商品标题
			params.body = type_body;  //商品描述
			// params.product_id = question_id; //订单id
			params.current_user_id = current_user_id;  //当前id
			params.metadata = {};
			params.metadata.pay_type = 'order';  //订单类型
			params.metadata.question_id = question_id;  //订单id
			var wechat_qr_params_url = "http://test.elvtuan.com/payment_gateway/charge";
			// var wechat_qr_params_url = jumpUrl+"/payment_gateway/charge";
			var qr_code_url;
		    $.post(wechat_qr_params_url,params,function(data){
		      },'json').error(function(data) {
		          var obj = $.parseJSON(data.responseText);
		          layer.msg(obj.error_messages);
		          console.info(obj);
		      }).success(function(data) {
			      	console.log(data);
			      	qr_code_url = data.credential.alipay_qr;
			      	  charge_id = data.id;
			      	  qr_payment_popup();
			      	  check_payment(charge_id);
			      	  var str = ''
			      	  str +='<img src="http://paysdk.weixin.qq.com/example/qrcode.php?data='+qr_code_url+'" style="width:250px;height:250px;" />';
			      	  str +='<p style="text-align:center;font-size:20px;">[ 扫描二维码支付 ]</p>';
			      	$(".content-box").append(str);
		      });
		}else{
			layer.msg("请选择付款类型");
      		return false;
		}
		stopDefault(e);
	});

	function check_payment(charge_id){
		var t1;
		var sum =0;
		function update_notify(){
				sum++;
				if(sum>600){window.clearInterval(t1);return false;}
				if(sum>180){
					m = sum%10;
					if(m!=0){return false;}
				}
				$(".sum").html(sum);
				var payment_query_url = jumpUrl + '/payment_gateway/query/'+charge_id;
			    $.get(payment_query_url, function(data){
			          
		        }, "json").error(function(data) {
	                var status_code = $.parseJSON(data.responseText);
	                layer.msg(status_code.message);
		        }).success(function(data) {
					console.log(data);
		            var obj = data;
		            if(obj.paid==true) {
		            	layer.msg("购买成功");
		            	window.location.href=jumpUrl+"/center/customer/my_order";
			        }
		        });
			}
			t1 = window.setInterval(function() {
				popup_visible = $(".content-box").is(":visible");
				if (popup_visible) {
					update_notify();
				}
				console.log('isvisible', $(".content-box").is(":visible"));
			},1000);
		window.onblur = function(){
			clearInterval(t1);
		}
		window.onfocus = function(){
			t1 = setInterval(function(){
				popup_visible = $(".content-box").is(":visible");
				if (popup_visible) {
					update_notify();
				}else{
					stopDefault();
				}
				console.log('isvisible', $(".content-box").is(":visible"));
			}, 1000 );
		}
	};

	// 微信扫码付费弹出框
	function qr_payment_popup(){
	 	var Popup02 = $(".content-box");
	 	layer.open({
          type: 1, //基本层类型  可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）。 若你采用layer.open({type: 1})方式调用，则type为必填项（信息框除外）
          title: false, //标题
          closeBtn: true,  //关闭按钮
          shade:0.3,  //遮罩默认是0.3透明度
          area: ['250px', '300px'],
          skin: 'yourclass', //样式类名
          content: Popup02 //内容
      	});
      	layerCss();
	};
	//抢单
	$(document).on( "click", ".js_to_take", function(e) { 
		var url = $(this).attr("data-href");
		var user_id = $(this).attr("data-id");
		var _token = $("input[name='_token']").val();
	    $.post(url,{"user_id":user_id,"_token":_token},function(data){
	      },'json').error(function(data) {
	          var obj = $.parseJSON(data.responseText);
	          $.each(obj.error_messages, function(i, item){
	          });
	      }).success(function(data) {
	          layer.msg(data.data);
	          window.location.href=jumpreplied;
	      });
	      stopDefault(e);
	});
	//受理
	$(document).on( "click", ".lv_accept", function(e) { 
		var url = $(this).attr("data-href");
		var user_id = $(this).attr("data-id");
		var _token = $("input[name='_token']").val();
	    $.post(url,{"user_id":user_id,"_token":_token},function(data){
	      },'json').error(function(data) {
	          var obj = $.parseJSON(data.responseText);
	          $.each(obj.error_messages, function(i, item){
	          });
	      }).success(function(data) {
	          layer.msg(data.data);
	          window.location.href=jumpaccept;
	      });
	      stopDefault(e);
	});
	//拒接
	$(document).on( "click", ".lv_refuse", function(e) { 
		var url = $(this).attr("data-href");
		var user_id = $(this).attr("data-id");
		var _token = $("input[name='_token']").val();
	    $.post(url,{"user_id":user_id,"_token":_token},function(data){
	      },'json').error(function(data) {
	          var obj = $.parseJSON(data.responseText);
	          $.each(obj.error_messages, function(i, item){
	          });
	      }).success(function(data) {
	          layer.msg("已拒接");
	          window.location.href=jumprefuse;
	      });
	      stopDefault(e);
	});

	// 请求列表
	get_question_list();
    function get_question_list(){
	  	var index = $(".load-more").attr("data-id");
	  	if (index == "1") {index = ""};
	  	var token =  JSON.parse(localStorage.getItem('token'));
	  	var question_list_url= apitest+"/user/question?type=creator&token="+token+"&size=8&page="+index;
	    var loading = '<div class="loading">加载中...</div>';
	    $(".question-list-box").append(loading);
	    $.get(question_list_url,function(data){
	      },'json').error(function(data){
	        var obj = $.parseJSON(data.responseText);
	        layer.msg(obj.error_messages);
	      }).success(function(data){
	        $(".loading").remove();
	        var obj = data.data;
	        // console.info(obj);
	        var length = obj.length;
	        var src = '';
	        if (obj.length>7) {
	                $(".load-more").css("display","block")
	              }else{
	                $(".load-more").css("display","none")
	              }
	        if (obj.length>0) {
	          for(var i = 0;i < obj.length; i++){
	            src +='<li>'
	              src +='<div class="oh">'
	                src +='<a href="'+jumpUrl+'/question/'+obj[i].id+'" class="question-title">'+obj[i].title+'</a>'
	                src +='<span class="fr colorD font16">'+obj[i].post_category_name+'</span>'
	              src +='</div>'
	              src +='<div class="colorD font14">回答'
	                src +='<span class="colorC"> '+obj[i].comments_count+'</span> '
	                src +='<span class="font16">• </span>收藏'
	                src +='<span class="colorC"> '+obj[i].collects_count+'</span>'
	                src +='<span style="margin-left: 20px;">'+obj[i].created_at+'</span>'
	              src +='</div>'
	            src +='</li>'
	          }
	          $(".question-list-box").append(src);
	        }else{
	        var str ='<li class="textac"><span class="colorB">暂无数据</span></li>';
	        $(".question-list-box").append(str);
	      }
	      });
  	}
  	 // 加载更多
    $(document).on("click",".load-more",function(e){
      index = parseInt($(".load-more").attr("data-id"))+1;
      $(".load-more").attr("data-id",index);
      get_question_list();
    });
});
